package com.hnkywl.sts.service.cwgl;

import com.google.gson.Gson;
import com.hnkywl.sts.dao.cwgl.KhzhsfmxDao;
import com.hnkywl.sts.dao.cwgl.XyzdrDao;
import com.hnkywl.sts.dao.zjgl.XyzfyDao;
import com.hnkywl.sts.entity.cwgl.Khzhsfmx;
import com.hnkywl.sts.entity.cwgl.VoucherItemData;
import com.hnkywl.sts.entity.sfgl.Sfk;
import com.hnkywl.sts.entity.sys.Yg;
import com.hnkywl.sts.entity.zjgl.Pj;
import com.hnkywl.sts.entity.zjgl.Xyz;
import com.hnkywl.sts.entity.zjgl.Xyzfy;
import com.hnkywl.sts.service.zjgl.XyzService;
import com.hnkywl.sts.util.BaseUtils;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: lenovo
 * Date: 13-6-3
 * Time: 下午3:13
 * To change this template use File | Settings | File Templates.
 */
@Service
public class XyzdrService {
    private XyzdrDao xyzdrDao;

    private XyzService xyzService;

    private KhzhsfmxDao khzhsfmxDao;

    private KhzhsfmxService khzhsfmxService;

    private XyzfyDao xyzfyDao;


    @Transactional
    public String findAllXyzdr(String xyzhm,Long gsId,Integer xyzdrZt,Integer  voucherNum,String czr,Integer xyzdrDrlx,int pageNo, int pageSize) {
       if(xyzdrDrlx==0){
           Page<Xyz> txcdPage = this.xyzdrDao.findAllXyzdr(xyzhm,gsId,xyzdrZt,voucherNum,czr,pageNo, pageSize);
           List<Xyz> xyzdrList = txcdPage.getResult() == null ? new ArrayList<Xyz>() : txcdPage.getResult();
           if(xyzdrList.size()>0){
               xyzdrList = getCzztByPj(xyzdrList);
           }
           String xyzdrJson = BaseUtils.fetchCollectionToJson(xyzdrList, "id", "nbgs.jc","sfk.gldw.jc",  "xyzhm",
                   "dqrq","dqje" ,"bzjbl","sfwffx","lxe","czzt","jkrq","sfdrlx", "kzf","createUser.xm", "dateCreated", "voucherNum");
           return "{\"total\":" + txcdPage.getTotalCount() + ",\"rows\":[" + xyzdrJson + "]}";
       }else{
           Page<Xyzfy> txcdPage = this.xyzfyDao.findAllXyzfy(xyzhm, gsId, xyzdrZt, voucherNum, czr, pageNo, pageSize);
           List<Xyzfy> xyzfyList = txcdPage.getResult() == null ? new ArrayList<Xyzfy>() : txcdPage.getResult();
           if(xyzfyList.size()>0){
               xyzfyList = getCzztByXyzfy(xyzfyList);
           }
           String xyzfyJson = BaseUtils.fetchCollectionToJson(xyzfyList, "id", "xyz.nbgs.jc",  "xyz.xyzhm",
                   "xyz.dqrq","xyz.dqje" ,"xyz.bzjbl","xyz.sfwffx","xyz.lxe","czzt","xyz.jkrq","xyz.sfdrlx", "kzf","createUser.xm", "dateCreated", "voucherNum");
           return "{\"total\":" + txcdPage.getTotalCount() + ",\"rows\":[" + xyzfyJson + "]}";
       }

    }

    public List<Xyz> getCzztByPj(List<Xyz> xyzList){
        for(Xyz p:xyzList){
            String czzt = "";
            if(p.getInsertFlag()==1 && p.getDeleteFlag()==1){
                czzt = "wdr";
            }else if(p.getInsertFlag()==1 && p.getDeleteFlag()==3){
                czzt = "sccg";
            }else if(p.getInsertFlag()==3 && p.getDeleteFlag()==1){
                czzt = "drcg";
            }else if(p.getInsertFlag()==2 && p.getDeleteFlag()==1 ||p.getInsertFlag()==2 && p.getDeleteFlag()==3 ){
                czzt = "drsb";
            }else if(p.getInsertFlag()==3 && p.getDeleteFlag()==2){
                czzt = "scsb";
            }else{
                czzt = "null";
            }
            p.setCzzt(czzt);
        }
        return xyzList;
    }

    public List<Xyzfy> getCzztByXyzfy(List<Xyzfy> xyzfyList){
        for(Xyzfy p:xyzfyList){
            String czzt = "";
            if(p.getInsertFlag()==1 && p.getDeleteFlag()==1){
                czzt = "wdr";
            }else if(p.getInsertFlag()==1 && p.getDeleteFlag()==3){
                czzt = "sccg";
            }else if(p.getInsertFlag()==3 && p.getDeleteFlag()==1){
                czzt = "drcg";
            }else if(p.getInsertFlag()==2 && p.getDeleteFlag()==1 ||p.getInsertFlag()==2 && p.getDeleteFlag()==3 ){
                czzt = "drsb";
            }else if(p.getInsertFlag()==3 && p.getDeleteFlag()==2){
                czzt = "scsb";
            }else{
                czzt = "null";
            }
            p.setCzzt(czzt);
        }
        return xyzfyList;
    }


    @Transactional
    public Map getVoucherMaster(Long id, Integer attachment, String uuid, String year, String mouth, Yg yg,Integer xyzdrDrlx) {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        String systemDate =simple.format(new Date());
        Map<String, Object> voucherMaster = new HashMap<String, Object>();
        voucherMaster.put("id", uuid);
        voucherMaster.put("vchrtypecode", "银行");//凭证类别
        voucherMaster.put("acctyear", year != null ? year : "");//会计年度
        voucherMaster.put("acctperiod", mouth != null ? mouth : "");//会计期间
        voucherMaster.put("createdate", systemDate);//凭证日期
        if(xyzdrDrlx==0){
            voucherMaster.put("unitcode", this.xyzService.findXyzDetail(id).getNbgs().getJiuqiUnitCode());//组织机构代码
        }else{
            voucherMaster.put("unitcode", this.xyzfyDao.get(id).getXyz().getNbgs().getJiuqiUnitCode());//组织机构代码
        }
        voucherMaster.put("acctbookcode", "01");//账薄标识
        voucherMaster.put("createuser", yg.getDlm());//制单人
        voucherMaster.put("attachment", attachment);//附件张数
        voucherMaster.put("memo", "");//备注
        if(xyzdrDrlx==0){
            voucherMaster.put("companyId",   this.xyzService.findXyzDetail(id).getNbgs().getId());//公司ID
        }else{
            voucherMaster.put("companyId",    this.xyzfyDao.get(id).getXyz().getNbgs().getId());//公司ID
        }
        return voucherMaster;
    }

    @Transactional
    public Map getVoucher(Long id, String uuid, List<VoucherItemData> voucherItemDataList,Integer xyzdrDrlx) {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String systemDate =simple.format(new Date());
        Xyz xyz = new Xyz();
        if(xyzdrDrlx==0){
             xyz = this.xyzService.findXyzDetail(id);
        }else{
           xyz = this.xyzfyDao.get(id).getXyz();
        }
        Map<String, Object> result = new HashMap<String, Object>();
        List<VoucherItemData> list = this.xyzdrDao.getVoucher(xyz,xyzdrDrlx);
        DecimalFormat df = new DecimalFormat("#.##");
        //凭证分录信息
        List<Map> items = new ArrayList<Map>();
        int order = 1;
        for (VoucherItemData item : list) {
            Map<String, Object> voucherItem = new HashMap<String, Object>();
            voucherItem.put("id", order);//唯一标识
            voucherItem.put("vchrid", uuid);//凭证主表ID
            voucherItem.put("itemorder", order);//分录编号
            voucherItem.put("subjectcode", item.getKmdm() != null && item.getKmdm() != null ? item.getKmdm() : "");//科目代码
            voucherItem.put("subjectname", item.getKmdm() != null && item.getKmmc() != null ? item.getKmmc() : "");//科目名称
            voucherItem.put("debit", item.getJf() != null ? df.format(item.getJf()) : 0.00);//借方金额
            voucherItem.put("credit", item.getDf() != null ? df.format(item.getDf()) : 0.00);//贷方金额
            voucherItem.put("qty", item.getQty() != null ? item.getQty() : 0);//数量
            voucherItem.put("price", 0);//单价
            voucherItem.put("currencycode", "CNY");//货币代码
            voucherItem.put("exchrate", 1.000000);//汇率
            voucherItem.put("orgnd", item.getJf() != null ? df.format(item.getJf()) : 0.00);//借方原币
            voucherItem.put("orgnc", item.getDf() != null ? df.format(item.getDf()) : 0.00);//贷方原币
            voucherItem.put("settlementcode", "");//结算方式代码
            voucherItem.put("settlementno", "");//结算号
            voucherItem.put("bizdate", simple.format(new Date()));//业务日期
            voucherItem.put("digest", item.getZy() != null ? item.getZy() : "");//摘要
            voucherItem.put("bizno", "");//业务号
            voucherItem.put("suppliername", item.getSupplierName() != null ? item.getSupplierName() : "");//供应商名称
            voucherItem.put("suppliercode", item.getSupplierCode() != null ? item.getSupplierCode() : "");//供应商代码
            voucherItem.put("departmentname", item.getDeptName() != null ? item.getDeptName() : "");//部门名称
            voucherItem.put("departmentcode", item.getDeptCode() != null ? item.getDeptCode() : "");//部门代码
            voucherItem.put("customername", item.getCustomerName() != null ? item.getCustomerName() : "");//客户名称
            voucherItem.put("customercode", item.getCustomerCode() != null ? item.getCustomerCode() : "");//客户代码
            voucherItem.put("staffname", item.getUserName() != null ? item.getUserName() : "");//职员名称
            voucherItem.put("staffcode", item.getUserCode() != null ? item.getUserCode() : "");//职员代码
            items.add(voucherItem);
            order++;
        }
        result.put("items", items);
        return result;
    }

    @Transactional
    public String findxyzdrFl(Long id,Integer xyzdrDrlx) {
        Xyz xyz = new Xyz();
        if(xyzdrDrlx==1){
             xyz = this.xyzfyDao.get(id).getXyz();
        }else{
             xyz = this.xyzService.findXyzDetail(id);
        }
        List<VoucherItemData> list = this.xyzdrDao.getVoucher(xyz,xyzdrDrlx);
        List<Map> txcdJson = new ArrayList<Map>();
        for (int i =0;i<list.size() ;  i++){
            VoucherItemData voucherItemData = list.get(i);
            Map<String, Object> voucherItem = new HashMap<String, Object>();
            voucherItem.put("zy",voucherItemData.getZy());
            voucherItem.put("km",voucherItemData.getKmmc());
            voucherItem.put("df",voucherItemData.getDf()==null?0:voucherItemData.getDf());
            voucherItem.put("jf",voucherItemData.getJf()==null?0:voucherItemData.getJf());
            txcdJson.add(voucherItem);
        }
        return new Gson().toJson(txcdJson);
    }

    @Transactional
    public Map getRevokeInfo(Long id,Integer xyzdrDrlx) {
        Map<String, Object> revokeInfo = new HashMap<String, Object>();
        if(xyzdrDrlx==0){
            Xyz  result = xyzdrDao.get(id);
            if (result == null) {
                throw new RuntimeException("没该公司的对照信息!");
            }
            revokeInfo.put("id", result.getUuid());//凭证ID
            revokeInfo.put("vchrid", result.getVoucherId());//凭证ID
            revokeInfo.put("unitcode", result.getNbgs().getJiuqiUnitCode());//单位代码
            revokeInfo.put("acctyear", result.getAcctyear());//会计年度
            return revokeInfo;
        }else{
            Xyzfy xyzfy = xyzfyDao.get(id);
            if (xyzfy == null) {
                throw new RuntimeException("没该公司的对照信息!");
            }
            revokeInfo.put("id", xyzfy.getUuid());//凭证ID
            revokeInfo.put("vchrid", xyzfy.getVoucherId());//凭证ID
            revokeInfo.put("unitcode", xyzfy.getXyz().getNbgs().getJiuqiUnitCode());//单位代码
            revokeInfo.put("acctyear", xyzfy.getAcctyear());//会计年度
            return revokeInfo;
        }
    }

    @Transactional
    public String revokeNote(Long xyzId) {
        String error = null;
        Xyz xyz = this.xyzService.findXyzDetail(xyzId);
        try {
            //信用证还款 信用证状态重置为已使用
            if(xyz.getStatus()==2){
                List<Khzhsfmx> khzhsfmxes = this.khzhsfmxDao.findKhzhsfmxByXyz(xyz.getId());
                this.khzhsfmxService.deleteKhzhsfmx(khzhsfmxes);
                xyz.setStatus(4);
                xyz.setLastUpdated(new Date());
                this.xyzService.saveOldXyz(xyz);
            }
            //信用证变现 信用证状态重置为新建
            if(xyz.getStatus()==3){
                List<Khzhsfmx> khzhsfmxes = this.khzhsfmxDao.findKhzhsfmxByXyz(xyz.getId());
                this.khzhsfmxService.deleteKhzhsfmx(khzhsfmxes);
                xyz.setStatus(1);
                xyz.setLastUpdated(new Date());
                this.xyzService.saveOldXyz(xyz);
            }
        } catch (Exception e) {
            error = e.getMessage();
        }
        return error;
    }

    @Autowired
    public void setXyzdrDao(XyzdrDao xyzdrDao) {
        this.xyzdrDao = xyzdrDao;
    }
    @Autowired
    public void setXyzService(XyzService xyzService) {
        this.xyzService = xyzService;
    }
    @Autowired
    public void setKhzhsfmxDao(KhzhsfmxDao khzhsfmxDao) {
        this.khzhsfmxDao = khzhsfmxDao;
    }
    @Autowired
    public void setKhzhsfmxService(KhzhsfmxService khzhsfmxService) {
        this.khzhsfmxService = khzhsfmxService;
    }
    @Autowired
    public void setXyzfyDao(XyzfyDao xyzfyDao) {
        this.xyzfyDao = xyzfyDao;
    }
}
